﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using JLL.China.Web.Libraries;
using System.Drawing;
using JLL.China.Infrastructure.Services;
using JLL.China.Model;
using System.Data.Linq;
namespace JLL.China.Web
{

    public class UploadImages : IHttpHandler
    {
        private bool IsDefaultImage = false;
        public string FormatFileName(string fullpath, string filename)
        {
            string file_ext = Path.GetExtension(fullpath);
            if (!File.Exists(fullpath))
            {
                IsDefaultImage = true;
                return filename + file_ext;
            }
            string new_file_name = "";
            string path = Path.GetDirectoryName(fullpath);


            for (int i = 1; i < 10; i++)
            {
                if (!File.Exists(path + "\\" + filename + "_" + i + file_ext))
                {
                    new_file_name = filename + "_" + i + file_ext;
                    return new_file_name;
                }
            }
            return new_file_name;
        }
        public void ProcessRequest(HttpContext context)
        {
            int folderId = Convert.ToInt32(context.Request.Form["folderId"]);
            string imgType = context.Request.Form["imageType"].ToString();
            string _strModule = context.Request.Form["folder"].ToString();
            HttpPostedFile file = context.Request.Files["FileData"];
            string mediaRootFolder = context.Request.Form["folder"];
            string mediaRootPath = context.Server.MapPath("~/Media/" + mediaRootFolder + "/");
            string storagePath = mediaRootPath + folderId.ToString();
            if (!Directory.Exists(storagePath))
            {
                Directory.CreateDirectory(storagePath);
                //Directory.Delete(storagePath);
            }
            // clearFolder(storagePath);

            string ext = System.IO.Path.GetExtension(file.FileName);
            string fullFilePath = storagePath + "\\" + folderId.ToString() + ext;

            string name_format = FormatFileName(fullFilePath, folderId.ToString());

            fullFilePath = storagePath + "\\" + name_format;

            //file.SaveAs(fullFilePath);
            //file.ContentLength
            Bitmap bitmap = new Bitmap(file.InputStream, false);
            Image orig = (Image)bitmap;

            //Resize
            HelperUtility.ThumbImage(orig, 650, orig.Width, orig.Height, fullFilePath);
            //
            Binary binaryObj = new Binary(ReadFile(fullFilePath));

            //case module
            //Listing
            if (_strModule == "Listings")
            {
                var media = new ListingMedia
                                {
                                    ListingsFID = decimal.Parse(folderId.ToString()),
                                    Filename = name_format,
                                    IsActive = true,
                                    IsDefault = IsDefaultImage,
                                    FileData = binaryObj,
                                    TypeOfUpload = "IMAGE",
                                    ImgType = imgType


                                };
                if (!imgType.Equals("Other Images"))
                {   /*delete listing media with imagetype in database**/
                    var mId1 = ListingMediaService.FindByListingID(folderId, imgType);
                    if (mId1 != 0)
                    {
                        var res = ListingMediaService.GetListingMediaById((int)mId1);
                        if (res != null)
                        {
                            ListingMediaService.Delete(res);
                            ListingMediaService.Save();

                        }
                    }
                }
                else
                {
                    if (!imgType.Equals("Cover image (Main)"))
                    {
                        media.IsDefault = true;
                    }
                }
                ListingMediaService.Create(media);
                ListingMediaService.Save();

            }
            // Directory
            if (_strModule == "ProjectDirectory")
            {
                var guidID = Guid.NewGuid();
                string a = guidID.ToString();
                var media = new ProjectDirectoryMedia
                {
                    ListingsFID = decimal.Parse(folderId.ToString()),
                    Filename = name_format,
                    IsActive = true,
                    IsDefault = IsDefaultImage,
                    FileData = binaryObj,
                    TypeOfUpload = "IMAGE",
                    GuiID = guidID,
                    ImgType = imgType
                };
                if (!imgType.Equals("Other Images"))
                {
                    /*delete property with imagetype in database**/
                    var mId = ProjectDirectoryMediaService.FindByListingID(folderId, imgType);
                    if (mId != 0)
                    {
                        var res = ProjectDirectoryMediaService.GetProjectDirectoryMediaById((int) mId);
                        if (res != null)
                        {
                            ProjectDirectoryMediaService.Delete(res);
                            ProjectDirectoryMediaService.Save();
                        }
                    }
                }
                else
                {
                    if (!imgType.Equals("Cover image (Main)"))
                    {
                        media.IsDefault = true;
                    }
                }
              
                ProjectDirectoryMediaService.Create(media);
                ProjectDirectoryMediaService.Save();
                //Update Link image for Project Directory table
                if (IsDefaultImage == true)
                {
                    var id = ProjectDirectoryMediaService.GetID(guidID);
                    var _oProjectItem = ProjectDirectoryService.FindById(folderId);
                    if (_oProjectItem != null)
                    {
                        _oProjectItem.HotImage_FID = id;
                        _oProjectItem.HotImage_Path = name_format;
                        ProjectDirectoryService.Update(_oProjectItem);
                        ProjectDirectoryService.Save();
                    }
                }
            }



            string fullThumPath = mediaRootPath + folderId.ToString() + "\\thumb";

            if (!Directory.Exists(fullThumPath))
            {
                Directory.CreateDirectory(fullThumPath);
            }

            //thumb
            string fullFileThumbPath = fullThumPath + "\\" + name_format;
            HelperUtility.ThumbImage(orig, 160, orig.Width, orig.Height, fullFileThumbPath);

            //
            context.Response.Write("Success");


        }

        private void clearFolder(string FolderName)
        {
            DirectoryInfo dir = new DirectoryInfo(FolderName);

            foreach (FileInfo fi in dir.GetFiles())
            {
                fi.Delete();
            }

            foreach (DirectoryInfo di in dir.GetDirectories())
            {
                clearFolder(di.FullName);
                di.Delete();
            }
        }
        //
        public byte[] imageToByteArray(System.Drawing.Image imageIn)
        {
            MemoryStream ms = new MemoryStream();
            imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            return ms.ToArray();
        }
        private byte[] ReadFile(string sPath)
        {
            //Initialize byte array with a null value initially.
            byte[] data = null;

            //Use FileInfo object to get file size.
            FileInfo fInfo = new FileInfo(sPath);
            long numBytes = fInfo.Length;

            //Open FileStream to read file
            FileStream fStream = new FileStream(sPath, FileMode.Open, FileAccess.Read);

            //Use BinaryReader to read file stream into byte array.
            BinaryReader br = new BinaryReader(fStream);

            //When you use BinaryReader, you need to supply number of bytes to read from file.
            //In this case we want to read entire file. So supplying total number of bytes.
            data = br.ReadBytes((int)numBytes);
            return data;
        }
        public Image byteArrayToImage(byte[] byteArray)
        {
            MemoryStream ms = new MemoryStream();

            ms = new MemoryStream(byteArray, 0, byteArray.Length);
            ms.Seek(0, SeekOrigin.Begin);
            System.Drawing.Image returnImage = System.Drawing.Image.FromStream(ms);
            return returnImage;
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
